package org.spring.boot.sample.hystrix.command;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy;
import com.netflix.hystrix.HystrixThreadPoolKey;

/**
 * 测试信号量隔离
 * 设置ExecutionIsolationSemaphoreMaxConcurrentRequests为3，意味着信号量最多允许执行run的并发数为3，超过则触发降级，即不执行run而执行getFallback
 * 设置FallbackIsolationSemaphoreMaxConcurrentRequests为1，意味着信号量最多允许执行fallback的并发数为1，超过则抛异常fallback execution rejected
 * @author guqj
 * 
 */
public class HystrixCommandSemaphore extends HystrixCommand<String> {

	private String name;

	public HystrixCommandSemaphore(String name) {
		super(
				Setter.withGroupKey(
						HystrixCommandGroupKey.Factory.asKey("SemaphoreGroup"))
						.andCommandKey(HystrixCommandKey.Factory.asKey("SemaphoreKey"))
						.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("SemaphoreThreadPoolKey"))
						.andCommandPropertiesDefaults(// 配置信号量隔离
								HystrixCommandProperties.Setter()
										.withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)
										.withExecutionIsolationSemaphoreMaxConcurrentRequests(3)
										.withFallbackIsolationSemaphoreMaxConcurrentRequests(1))
		);
		this.name = name;
	}

	@Override
	protected String run() throws Exception {
		return "run(): name="+name+"，线程名是" + Thread.currentThread().getName();
	}


	@Override
	protected String getFallback() {
		return "getFallback(): name="+name+"，线程名是" + Thread.currentThread().getName();
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
